#include <iostream>
#include <memory>
using namespace std;

template<typename T>
class Vector {
private:
    static std::allocator<T> _alloc;
    T *_start;                 //指向数组中的第一个元素
    T *_finish;                //指向最后一个实际元素之后的那个元素
    T *_end_of_storage;        //指向数组本身之后的位置

public:
    using iterator = T*;

    iterator begin(){
        return _start;
    }
    iterator end(){
        return _finish;
    }


    Vector();

    ~Vector();

    void push_back(const T &);

    void pop_back();

    int size()const;

    int capacity()const;

    void display(){
        for (int i = 0; i < size(); ++i) {
            cout << _start[i] << " ";
        }
        cout << endl;
    }

private:
    void reallocate();//重新分配内存,动态扩容要用的

};

template<typename T>
std::allocator<T> Vector<T>::_alloc;

template<typename T>
Vector<T>::Vector():_start(nullptr), _finish(nullptr), _end_of_storage(nullptr) {
}
template<typename T>
Vector<T>::~Vector(){
    if(_start){
        while (_start != _finish){
            /* 因为有可能存的是对象，所以需要一个一个释放 */
            _alloc.destroy(--_finish);
        }
        _alloc.deallocate(_start, capacity());
    }
}

template<typename T>
void Vector<T>::push_back(const T &value) {
    /* 是不是满的 */
    if (size() == capacity()) {
        /* 需要扩容 */
        reallocate();
    }
    if (size() < capacity()) {
        /* 在vector尾部构建对象 */
        _alloc.construct(_finish++, value);
    }
}

template<typename T>
void Vector<T>::pop_back() {
    _alloc.destroy(--_finish);
}

template<typename T>
int Vector<T>::size()const {
    return _finish - _start;
}

template<typename T>
int Vector<T>::capacity()const {
    return _end_of_storage - _start;
}

template<typename T>
void Vector<T>::reallocate() {
    /**
     * 1. 2倍扩容
     * 2. 复制数据
     * 3. 销毁空间
     * 4. 回收空间
     * 5. 更新指针
     */
    int oldCapacity = capacity();
    int newCapacity = oldCapacity > 0 ? 2 * oldCapacity : 1;
    T* ptmp =  _alloc.allocate(newCapacity);

    if(_start){
        uninitialized_copy(_start, _finish, ptmp);
        while (_start != _finish){
//            _alloc.destroy(_start++);
            _alloc.destroy(--_finish);
        }
        _alloc.deallocate(_start, oldCapacity);
    }

    _start = ptmp;
    _finish = ptmp + oldCapacity;
    _end_of_storage = ptmp + newCapacity;
}



int main() {
    Vector<int> vec;
    vec.push_back(3);
    vec.push_back(2);
    vec.push_back(5);
    vec.push_back(8);
    vec.push_back(4);
    vec.push_back(7);

//    vec.display();
    for(auto& elem: vec){
        cout << elem << " ";
    }
    return 0;
}
